<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { taskApi, templateApi } from '@/api'
import { showToast } from 'vant'

const testResults = ref([])
const testing = ref(false)

// 屏幕信息（避免在模板中直接访问window）
const screenWidth = ref(0)
const screenHeight = ref(0)
const dpr = ref(1)
const isMobile = ref(false)

const updateScreenInfo = () => {
  if (typeof window !== 'undefined') {
    screenWidth.value = window.innerWidth
    screenHeight.value = window.innerHeight
    dpr.value = window.devicePixelRatio || 1
    isMobile.value = typeof navigator !== 'undefined' && /Mobile/i.test(navigator.userAgent)
  }
}

onMounted(() => {
  updateScreenInfo()
  if (typeof window !== 'undefined') {
    window.addEventListener('resize', updateScreenInfo)
  }
})

onUnmounted(() => {
  if (typeof window !== 'undefined') {
    window.removeEventListener('resize', updateScreenInfo)
  }
})

const addResult = (test, success, message) => {
  testResults.value.push({
    test,
    success,
    message,
    time: new Date().toLocaleTimeString()
  })
}

const testAPI = async () => {
  testing.value = true
  testResults.value = []

  // 测试任务API
  try {
    const tasks = await taskApi.getTaskList({ pageNo: 1, pageSize: 5 })
    addResult('任务列表API', true, `成功获取 ${tasks.records?.length || 0} 条任务`)
  } catch (error) {
    addResult('任务列表API', false, error.message)
  }

  // 测试模板API
  try {
    const templates = await templateApi.getTemplateList({ pageNo: 1, pageSize: 5 })
    addResult('模板列表API', true, `成功获取 ${templates.records?.length || 0} 条模板`)
  } catch (error) {
    addResult('模板列表API', false, error.message)
  }

  // 测试创建任务
  try {
    const taskData = {
      taskName: '测试任务_' + Date.now(),
      customsCode: '0000',
      subscribeMode: 'RAW',
      dataFormat: 'CSV',
      dataSource: '日库',
      selectedFields: ['entry_id', 'g_no', 'i_e_flag'],
      conditions: '{"test": true}',
      scheduleType: 'DAILY',
      scheduleTime: '10:00'
      // 可选: templateId, groupFields, numericAggFields, scheduleCron
    }

    const result = await taskApi.saveTask(taskData)
    addResult('创建任务API', true, `成功创建任务`)

    // 注意：不自动删除，因为可能需要查看创建的数据
  } catch (error) {
    addResult('创建任务API', false, error.message)
  }

  testing.value = false
  showToast('API测试完成')
}
</script>

<template>
  <div class="page-container">
    <van-nav-bar title="API连接测试" />

    <div style="padding: 16px;">
      <van-button
        type="primary"
        block
        :loading="testing"
        @click="testAPI"
      >
        开始测试API连接
      </van-button>

      <van-cell-group style="margin-top: 16px;" v-if="testResults.length > 0">
        <van-cell
          v-for="(result, index) in testResults"
          :key="index"
          :title="result.test"
          :label="result.message"
          :value="result.time"
        >
          <template #right-icon>
            <van-icon
              :name="result.success ? 'success' : 'close'"
              :color="result.success ? '#07c160' : '#ee0a24'"
            />
          </template>
        </van-cell>
      </van-cell-group>

      <van-divider style="margin: 24px 0;">移动端适配测试</van-divider>

      <van-cell-group>
        <van-cell title="屏幕宽度" :value="screenWidth + 'px'" />
        <van-cell title="屏幕高度" :value="screenHeight + 'px'" />
        <van-cell title="设备像素比" :value="dpr" />
        <van-cell title="用户代理" :value="isMobile ? '移动设备' : '桌面设备'" />
      </van-cell-group>

      <van-divider style="margin: 24px 0;">UI组件测试</van-divider>

      <van-cell-group>
        <van-cell title="按钮测试">
          <template #right-icon>
            <van-button size="small" type="primary">主要</van-button>
            <van-button size="small" type="success" style="margin-left: 8px;">成功</van-button>
          </template>
        </van-cell>

        <van-cell title="标签测试">
          <template #right-icon>
            <van-tag type="primary">主要</van-tag>
            <van-tag type="success" style="margin-left: 8px;">成功</van-tag>
            <van-tag type="warning" style="margin-left: 8px;">警告</van-tag>
          </template>
        </van-cell>

        <van-cell title="图标测试">
          <template #right-icon>
            <van-icon name="success" color="#07c160" />
            <van-icon name="cross" color="#ee0a24" style="margin-left: 8px;" />
            <van-icon name="info-o" color="#1989fa" style="margin-left: 8px;" />
          </template>
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>

<style scoped>
.van-cell-group {
  margin-bottom: 12px;
}
</style>
